<template>
  <div class="zy-content">
    <div class="search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">{{ $t('common.UseLocation') }}</p>
            <div class="ipt">
              <Cascader clearable :data="orgList" v-model="params.orgCode"
                        :placeholder="`${$t('common.selectInfo')}`" change-on-select>
              </Cascader>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('设备') }}</p>
            <div class="ipt">
              <Select v-model="params.deviceMId" filterable clearable
                      :placeholder="`${$t('common.inputInfo')}${$t('equipCheck.SerialNo')}`"
                      :remote-method="handleRemote1"
                      :loading="searchLoading">
                <Option v-for="(item, i) in deviceParamsList"
                        :value="item.deviceMId"
                        :disabled="item.disabled"
                        :label="item.desc"
                        :tag="item"
                        :key="i">
                </Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('MAC地址') }}</p>
            <div class="ipt">
              <Input type="text" v-model="params.padNo" :placeholder="`${$t('common.inputInfo')}`" class="inputBorder"/>
            </div>
          </div>

        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button class="search-btn" type="primary" @click="searchList">
                {{ $t('common.Query') }}
              </Button>
              <Button
                  class="reset-btn"
                  @click="reset()"
              >{{ $t('common.reset') }}
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button @click="associatedDevice">{{ $t('common.New') }}</Button>
          <Button @click="getTableColumns(columns)">
              {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
          </Button>
      </div>
      <div class="tableContent">
        <Table ellipsis ref="selection" class="resizable-table" border @on-column-width-resize="onColumnWidthResize" :columns="columnsList" :data="list">
          <template slot-scope="{ row}" slot="action">
            <auto-place-children>
               <span class="operationBtn" @click="associatedDevice(row)">
                 <i class="iconfont zy-common-bianji"></i>
                 {{ $t('关联设备') }}</span>
            </auto-place-children>
          </template>
        </Table>
      </div>
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total"/>
        <Page :total="total" :page-size="params.pageSize" :page-size-opts="pageSizeOption" :current="params.pageNum"
              @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total/>
      </div>
    </div>
    <Modal :mask-closable="false"
        v-model="associatedDeviceStatus"
        :title="$t('关联设备')"
        class="modal-content-layout"
        width="1200px"
        :scrollable="true"
    >

      <Form class="formList" ref="form" :model="form" label-position="top">

        <Row :gutter="24">
          <Col span="6">
            <FormItem :label="$t('MAC地址')" required>
              <Input type="text" v-model="form.padNo" :placeholder="`${$t('common.inputInfo')}`" class="inputBorder"/>
            </FormItem>
          </Col>
        </Row>
        <FormItem>
          <div class="search-box-layout noPad" >
            <Row :gutter="24">
              <Col span="6">
                <div>
                  <p class="label">{{ $t('common.UseLocation') }}</p>
                  <div class="ipt">
                    <Cascader clearable :data="orgList" v-model="associatedParams.orgCode"
                              :placeholder="`${$t('common.selectInfo')}`" change-on-select>
                    </Cascader>
                  </div>
                </div>
              </Col>
              <Col span="6">
                <div>
                  <p class="label">{{ $t('设备') }}</p>
                  <div class="ipt">
                    <Select v-model="associatedParams.deviceMId" filterable clearable
                            :placeholder="`${$t('common.inputInfo')}${$t('equipCheck.SerialNo')}`"
                            :remote-method="handleRemote"
                            :loading="searchLoading"
                            @on-select="handleChangeWl">
                      <Option v-for="(item, i) in numberList"
                              :value="item.deviceMId"
                              :disabled="item.disabled"
                              :label="item.desc"
                              :tag="item"
                              :key="i">
                      </Option>
                    </Select>
                  </div>
                </div>
              </Col>
              <Col span="6">
                <div>
                  <p class="label hide-label">--</p>
                  <div class="ipt">
                    <Button class="search-btn" type="primary" @click="searchUnbindDevice">
                      {{ $t('common.Query') }}
                    </Button>
                    <!--                <Button-->
                    <!--                    class="reset-btn"-->
                    <!--                    @click="reset()"-->
                    <!--                >{{ $t('common.reset') }}-->
                    <!--                </Button>-->
                  </div>
                </div>
              </Col>
            </Row>
          </div>
        </FormItem>
        <FormItem>
          <div class="deviceWrap">
            <div class="deviceItemWrap" style="margin-right: 20px">
              <Table height="300"  ref="selection" :columns="columnsDevice" :data="unBindList">
                <template slot-scope="{ row,index}" slot="action">
                  <auto-place-children>
               <span style="cursor: pointer" class="operationBtn" @click="addDevice(row,index)">
                 <i class="iconfont zy-common-bianji"></i>{{ $t('新增') }}</span>
                  </auto-place-children>
                </template>
              </Table>
            </div>
            <div class="deviceItemWrap">
              <Table height="300"  ref="selection" :columns="columnsDevice" :data="bindList">
                <template slot-scope="{ row, index}" slot="action">
                  <auto-place-children>
               <span style="cursor: pointer" class="operationBtn" @click="removeDevice(row,index)">
                 <i class="iconfont ivu-icon ivu-icon-ios-md-add"></i>{{ $t('删除') }}</span>
                  </auto-place-children>
                </template>
              </Table>
            </div>
          </div>
        </FormItem>

      </Form>
      <div slot="footer">
        <Button type="default" @click="associatedDeviceStatus = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="saveAssociatedDevice">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" class="modal-title-layout" v-model="deleteShow" :title="`${$t('common.Delete')}`">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{$t('是否删除该绑定关系')}}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="deleteShow = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary"
                @click="submitRemoveDevice ">{{ $t('maintenance.Confirmed') }}
        </Button>
      </div>
    </Modal>
  </div>
</template>


<script>
import recursion from "@/util/recursion";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "padmanage",
    mixins:[toggleTableOperation],
  data() {
    return {
      columns: [
        {
          title: this.$t('位置'),
          key: "position6",
          align: "center",
            resizable: true
        },
        {
          title: this.$t('MAC地址'),
          key: "padNo",
          align: "center",
            resizable: true
        },
        {
          title: this.$t('关联设备'),
          key: "deviceMId",
          align: "center",
            resizable: true
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          width: 200,
          align: "center"
        }
      ],
      list: [],
      params: {
        pageNum: 1,
        pageSize: 10
      },
      associatedDeviceStatus: false,
      total: 0,
      associatedParams: {},
      form: {},
      orgList: [],
      columnsDevice: [
        {
          title: this.$t('安装位置'),
          key: "position4",
          align: "center",
          width:200
        },
        {
          title: this.$t('设备流水号'),
          key: "deviceMId",
          align: "center",
          width:190
          // tooltip: true
        },
        {
          title: this.$t('设备编号'),
          key: "deviceNo",
          align: "center",
          width:200
          // tooltip: true
        },
        {
          title: this.$t('设备名称'),
          key: "deviceName",
          align: "center",
          width:150
          // tooltip: true
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          width: 90,
          align: "center",
          fixed:"right"
        }
      ],
      numberList: [],
      searchLoading: false,
      unBindList: [],
      bindList: [],
      deviceParamsList: [],
      deleteShow:false,
      activeItem:{}
    }
  },
    created() {
      this.getTableColumnsWidth(this.columns)
    },
    mounted() {
    this.getList()

    this.getOrgList()
  },
  methods: {
    submitRemoveDevice(){
      this.axios({
        method: 'post',
        url: '/dms/padBinding/del',
        data: {ids: [this.activeItem.id]}
      }).then(res => {
        if (res.code === 200) {
          this.deleteShow = false
          this.bindList.splice(this.activeItem.index, 1)
          this.searchUnbindDevice()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    addDevice(row, index) {
      this.bindList.push(row)
      this.unBindList.splice(index, 1)
      // this.filterUnbindList()
    },
    removeDevice(row, index) {
      this.activeItem = {
        ...row,index
      }
      this.deleteShow = true
    },
    saveAssociatedDevice() {
      if (!this.form.padNo) {
        this.$Message.warning(({content: this.$t('请输入MAC地址'), duration: 6, closable: true}));
        return;
      }

      if (this.bindList.length < 1){
        if ( !this.form.id){
          this.$Message.warning(({content: this.$t('请关联设备'), duration: 6, closable: true}));
          return;
        }else{
          this.associatedDeviceStatus = false;
          this.bindList = []
          this.unBindList = []
          this.form = {}
          this.getList()
          return;
        }

      }
      let params = this.bindList.map(item => {
        return {
          orgCode: item.orgCode,
          padNo: this.form.padNo,
          deviceMId: item.deviceMId,
          padNoOld: this.form.padNoOld,
        }
      })

      this.axios({
        method: 'post',
        url: '/dms/padBinding/add',
        data: params
      }).then(res => {
        // this.loading = false;
        if (res.code === 200) {
          this.associatedDeviceStatus = false;
          this.$Message.success(res.msg);
          this.bindList = []
          this.unBindList = []
          this.form = {}
          this.getList()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    associatedDevice(row) {
      this.associatedParams = {}
      this.bindList = []
      this.unBindList = []
      this.associatedDeviceStatus = true
      this.form.padNo = row.padNo
      this.form.id = row.id
      this.form.padNoOld = row.padNo
      this.getOrgList()
      if (row.id)
        this.searchUnbindDevice()
    },
    filterUnbindList() {
      // let list = this.unBindList.filter(item=>{
      //   const status =  this.bindList.find(m=> m.deviceMId === item.deviceMId)
      //   if (!status){
      //     return item;
      //   }
      // })
      // this.unBindList = list
    },
    searchUnbindDevice() {
      if (!this.form.padNo) {
        this.$Message.warning(({content: this.$t('请输入MAC地址'), duration: 6, closable: true}));
        return;
      }
      let params = this.associatedParams
      if (Array.isArray(params.orgCode))
        params.orgCode = params.orgCode[params.orgCode.length - 1]
      if (Array.isArray(this.bindList)){
        params.rightDeviceMIds = this.bindList.map(item=> {
          return item.deviceMId
        })
      }
      this.axios({
        method: 'post',
        url: '/dms/padBinding/queryDevice',
        data: {...this.associatedParams,padNo:this.form.padNo}
      }).then(res => {
        if (res.code === 200) {
          let {noBinding, binding} = res.data;
          this.unBindList = noBinding
          if (this.bindList.length < 1) {
            this.bindList = binding
          }
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    handleChangeWl(val) {
      const {deviceMId, deviceNo} = val.tag || {}
      if (deviceMId)
        this.associatedParams = {
          ...this.associatedParams,
          deviceMId,
          deviceNo
        }
      else {
        delete this.associatedParam.deviceMId
        delete this.associatedParam.deviceNo
      }
    },
    handleRemote1(query) {
      if (query !== "") {
        this.searchLoading = true;
        let _query = query.split('-')
        if (Array.isArray(_query)) _query = _query[0]
        return this.axios({
          method: "get",
          url: "/dms/dmsDevice/deviceList",
          params: {
            deviceMId: _query,
            deviceNo: '',
            assetsNo: "",
            orgCode: ''
          },
        }).then((res) => {
          if (res.code === 200) {
            this.deviceParamsList = res.data.map(item => {
              item.desc = item.deviceMId + '-' + item.deviceNo + '-' + item.deviceName
              return item;
            })
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true,
            });
          }
        })
            .finally(() => {
              this.searchLoading = false;
            });
      } else {
        this.numberList = [];
      }
    },
    handleRemote(query) {
      if (query !== "") {
        this.searchLoading = true;
        let _query = query.split('-')
        if (Array.isArray(_query)) _query = _query[0]
        return this.axios({
          method: "get",
          url: "/dms/dmsDevice/deviceList",
          params: {
            deviceMId: _query,
            deviceNo: '',
            assetsNo: "",
            orgCode: ''
          },
        }).then((res) => {
          if (res.code === 200) {
            this.numberList = res.data.map(item => {
              item.desc = item.deviceMId + '-' + item.deviceNo + '-' + item.deviceName
              return item;
            })
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true,
            });
          }
        })
            .finally(() => {
              this.searchLoading = false;
            });
      } else {
        this.numberList = [];
      }
    },
    getOrgList() {
      this.axios({
        method: 'get',
        url: '/basic/organization/findListByToken',
        params: {level: 3}
      }).then(res => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'code',
            children: 'children'
          }
          this.orgList = recursion.convertTree(res.data, obj)
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    reset() {
      this.params = {
        pageSize: this.params.pageSize,
        pageNum: this.params.pageNum,
      }
      this.getList()
    },
    searchList() {
      this.params.pageNum = 1
      this.getList()
    },
    changePageSize(pageSize) {
      this.params.pageSize = pageSize;
      this.getList();
    },
    changePageNum(val) {
      this.params.pageNum = val;
      this.getList();
    },
    getList() {
      let params = {
        ...this.params
      };

      if (Array.isArray(params.orgCode))
        params.orgCode = params.orgCode[params.orgCode.length - 1]

      this.axios({
        method: 'post',
        url: '/dms/padBinding/list',
        data: params
      }).then(res => {
        if (res.code === 200) {
          this.list = res.data.list
          this.total = res.data.total
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.deviceWrap {
  .deviceItemWrap {
    display: inline-block;
    width: calc(50% - 10px);
    vertical-align: top;
  }
}
</style>
